package com.robooot.business_counter.service;

import com.robooot.business_counter.dao.StoreDao;
import com.robooot.business_counter.entity.Config;
import com.robooot.business_counter.util.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ConfigService {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private StoreDao storeDao;
    @PostConstruct
    public void init() {
        List<Config> configs = storeDao.getAllConfig();
        Map<String, String> map = new HashMap<>();
        configs.forEach(e -> {
            String key = String.format("%s_config:provider:%s",e.getConfigName(),e.getProviderId());
            String value = e.getConfigInfo();
            redisTemplate.opsForValue().set(key,value);
        });
    }

    public Map<String, String> getConfig(String configName, String providerId) {
        String key = String.format("%s_config:provider:%s",configName,providerId);
        Object jsonObject = redisTemplate.opsForValue().get(key);
        Map<String, String> result = new HashMap<>();
        if (jsonObject != null) {
            result = JsonUtils.getObjectFromJson(jsonObject.toString(),Map.class);
        }
        return result;
    }
}
